package com.tianhui.consignortwofei.utils.shuiyin;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;

import com.tianhui.consignortwofei.R;

/**
 * @author fei
 * @date 2024/3/25
 * @description
 */
public class WatermarkDrawable extends Drawable {
    private String watermarkText;
    private Paint paint;
    private boolean isOne;
    private int numX, numY;
    private int mWidth, mHeight, mOffSet, textWidth, textHeight;
    private Context mContext;

    public WatermarkDrawable(Context context, String text, boolean isOne) {
        watermarkText = text;
        mContext = context;
        this.isOne = isOne;
        paint = new Paint();
        paint.setColor(context.getResources().getColor(R.color.colorBlueLight));
        paint.setTextSize(25);
        paint.setAlpha(100);
        textWidth = (int) paint.measureText(watermarkText);
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        textHeight = (int) (fontMetrics.descent - fontMetrics.ascent);
        Resources resources = mContext.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        mWidth = dm.widthPixels;
        mHeight = dm.heightPixels;
        mOffSet = ((mHeight - mWidth) >> 1);

        int max = Math.max(mWidth, mHeight);
        numX = max / (textWidth + 50) + 2;
        numY = max / (textHeight + 100) + 2;
    }

    @Override
    public void draw(Canvas canvas) {
        if (isOne) {
            drawOneWaterMark(canvas);
        } else {
            drawFullWaterMark(canvas);
        }
    }

    private void drawOneWaterMark(Canvas canvas) {
        int width = getBounds().width();
        int height = getBounds().height();

        float textWidth = paint.measureText(watermarkText);
        float x = (width - textWidth) / 2;
        float y = height / 2;

        canvas.drawText(watermarkText, x, y, paint);
    }

    private void drawFullWaterMark(Canvas canvas) {
        for (int i = 0; i < numY; i++) {
            int yy = (100 >> 1) + (100 + textHeight) * i;
            for (int j = 0; j < numX; j++) {
                float xx = (i % 2) * (50 + textWidth) / 2 + j * (50 + textWidth);
                canvas.drawText(watermarkText, xx, yy, paint);
            }
        }
    }


    @Override
    public void setAlpha(int alpha) {
        paint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        paint.setColorFilter(colorFilter);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }
}

